package cn.hua.trip.app.base.controller;

import cn.hua.trip.app.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.util.HashMap;

/**
 * 文件上传的控制器,上传成功之后的图片是存到了指定的路径,并未保存到数据库中
 *
 * 这点要注意
 */

@RestController
@RequestMapping("images")
public class ImageController {

    @Autowired
    private ServletContext ctx;

    @PostMapping
    public Object uploadImage(MultipartFile pic){
        //要得到的数据为{"url":"/upload/xxx.jpg","status:1"}这种格式的数据,status为上传成功失败的状态
        HashMap<Object, Object> map = new HashMap<Object,Object>();

        try{
            //成功
            //上传的文件形式为  f:/image//upload/xxx.jpg
            String imagePath = UploadUtil.upload(pic,UploadUtil.IMG_BASE_PATH+"upload");
            map.put("url",imagePath);
            map.put("status",1);
        }catch (Exception e){
            //失败
            e.printStackTrace();
            map.put("url","");
            map.put("status",0);
        }
        return map;
    }

}
